package com.whynot.frame.basic.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.util.*;

public class OSSClientUtils {
    //log
    private static final Logger log = Logger.getLogger(OSSClientUtils.class);
    //阿里云API的内或外网域名
    private static String ENDPOINT;
    //阿里云API的密钥Access Key ID
    private static String ACCESS_KEY_ID;
    //阿里云API的密钥Access Key Secret
    private static String ACCESS_KEY_SECRET;
    //初始化OssClient
    private static OSSClient ossClient;
    public static  String dir = "data";
    public static  String workName = "whynot-3";
    //init static datas
    static{
       /* ResourceBundle bundle = PropertyResourceBundle.getBundle("oss.properties");
        ENDPOINT = bundle.containsKey("endpoint") == false ? "" : bundle.getString("endpoint");
        ACCESS_KEY_ID = bundle.containsKey("accessKeyId") == false? "" : bundle.getString("accessKeyId");
        ACCESS_KEY_SECRET = bundle.containsKey("accessKeySecret") == false ? "" : bundle.getString("accessKeySecret");*/
        ENDPOINT ="http://oss-cn-shanghai.aliyuncs.com"; //= "http://oss-cn-beijing.aliyuncs.com";
        ACCESS_KEY_ID ="LTAIb0zTl3G5u3St"; //= "LTAIzaeycZoqNi5C";
        ACCESS_KEY_SECRET ="6jXkQMKOHNATWeDXnejVA8NyD9moF6";//= "n5la9yUm4X3aR75EZO2R0rjaCrljYI";
        ossClient =  new OSSClient(ENDPOINT,ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    }
    /**
     * 根据图片地址上传图片
     * @param url
     * @throws FileNotFoundException
     */
    public void uploadImg2Oss(String bucketName,String fDir,String url) throws FileNotFoundException {
        File fileOnServer = new File(url);
        FileInputStream fin;
        try {
            fin = new FileInputStream(fileOnServer);
            String[] split = url.split("/");
            this.uploadFile2OSS(bucketName,fDir,fin, split[split.length - 1]);
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("图片上传失败");
        }
    }
    /**
     * 根据文件流上传图片，主要应用于SpringMVC提交的MultipartFile文件
     * @param bucketName
     * @param fDir
     * @param request
     * @return
     * @throws FileNotFoundException
     */
    public String uploadImg2Oss(String bucketName,String fDir,HttpServletRequest request) throws FileNotFoundException {
        MultipartFile file = getFile(request);
        if (file.getSize() > 2 * 1024 * 1024) {
            throw new FileNotFoundException("上传图片大小不能超过2M！");
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(bucketName,fDir,inputStream, name);
            return name;
        } catch (Exception e) {
            throw new FileNotFoundException("图片上传失败");
        }
    }
    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     *
     * @param instream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadFile2OSS(String bucketName,String fDir,InputStream instream, String fileName) {
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            setParams(bucketName,fDir);
            //上传文件
            log.info(dir + "/" + fileName);
            PutObjectResult putResult = ossClient.putObject(workName, dir + "/"  + fileName, instream, objectMetadata);
            ret = putResult.getETag();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }
    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }
    /**
     * 获得图片路径，也就是OSS文件的key
     * @param fileUrl
     * @return
     */
    public String  getImgUrl(String bucketName,String fDir,String fileUrl) {
        if (null != fileUrl && "" != fileUrl) {
            String[] split = fileUrl.split("/");
            if(null != fDir && "" != fDir){
                this.dir = fDir;
            }
            return this.getUrl(bucketName,dir+ "/" + split[split.length - 1]);
        }
        return null;
    }
    /**
     * 获得url链接
     *
     * @param key 路径+文件名
     * @return
     */
    public String getUrl(String bucketName, String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        setParams(bucketName,"'");
        // 生成URL
        URL url = ossClient.generatePresignedUrl(workName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }
    /**
     * 新建Bucket  --Bucket权限:私有
     * @param bucketName bucket名称
     * @return true 新建Bucket成功
     * */
    public boolean createBucket( String bucketName){
        setParams(bucketName,"");
        Bucket bucket = ossClient.createBucket(workName);
        return bucketName.equals(bucket.getName());
    }
    /**
     * 创建权限Bucket
     * @param request
     * @param buckName
     * @return
     */
    public boolean createAclBucket(String buckName,CreateBucketRequest request){
        Bucket bucket =  ossClient.createBucket(request);
        return bucket.getName().equals(buckName);
    }
    /**
     * 创建权限Bucket
     * @param auth
     * CannedAccessControlList.PublicRead公公读写
     * CannedAccessControlList.PublicReadWrite公共读
     * @param bucketName
     * @return
     */
    public boolean createAclBucket(String bucketName, String auth){
        setParams(bucketName,"");
        CreateBucketRequest request = new CreateBucketRequest(workName);
        CannedAccessControlList acl = CannedAccessControlList.parse(String.valueOf(auth));
        request.setCannedACL(acl);
        Bucket bucket =  ossClient.createBucket(request);
        return bucket.getName().equals(workName);
    }
    /**
     * 根据key获取OSS服务器上的文件输入流
     * @param bucketName bucket名称
     * @param key Bucket下的文件的路径名+文件名
     */
    public InputStream getOSS2InputStream(String bucketName,String fDir, String key){
        setParams(bucketName,fDir);
        OSSObject ossObj = ossClient.getObject(workName,  dir+"/"+key);
        return ossObj.getObjectContent();
    }
    /**
     * 根据key获取OSS服务器上的文件输入流
     * @param bucketName bucket名称
     * @param key Bucket下的文件的路径名+文件名
     */
    public String getOSS2Url(String bucketName,String fDir, String key){
        setParams(bucketName,fDir);
        OSSObject ossObj = ossClient.getObject(workName,  dir+ "/"+key);
        return ossObj.getResponse().getUri();
    }
    /**
     * 参数判断
     * @param bucketName
     * @param fDir
     */
    private void setParams(String bucketName,String fDir){
        if(null != fDir && "" != fDir){
            this.dir = fDir;
        }
        if(null != bucketName && "" != bucketName){
            this.workName = bucketName;
        }
    }
    /**
     * 获取上传的文件
     * @param request
     * @return
     */
    public MultipartFile getFile(HttpServletRequest request){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Set<String> strings = fileMap.keySet();
        Iterator<String> iterator = strings.iterator();
        MultipartFile multipartFile = null;
        while (iterator.hasNext()) {
            String next = iterator.next();
            multipartFile = fileMap.get(next);
        }
        return multipartFile;
    }
    public static void main(String[] args) {
        OSSClientUtils ossClientUtil = new OSSClientUtils();
        ossClientUtil.createAclBucket(ossClientUtil.workName,String.valueOf(CannedAccessControlList.PublicRead));
    }
}